package com.nuanshui.heatedloan.msgcenter.model;

import com.alibaba.fastjson.annotation.JSONField;
import org.apache.commons.lang3.RandomUtils;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

public class VeriCode implements Serializable {

	private static final long serialVersionUID = 1L;

	private  String smsCode;//要发送的短信验证码内容
	private  Date validDate;//验证短信验证码是否过期的时间
	private  Calendar canSendDate;//短信是否可以发送的时间
	private  String mobile;//要发送的短信手机号

	private Integer length;//验证码长度

	public VeriCode() {
	}

	public VeriCode(String mobile) {
		this.mobile = mobile;
		smsCode = "" + RandomUtils.nextInt(100000, 1000000);
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.SECOND, 3600);
		validDate = cal.getTime();
		canSendDate = Calendar.getInstance();

		length=smsCode.length();
	}
	
	public VeriCode(String mobile, Integer length){
		this.mobile = mobile;
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<length; i++){
			sb.append(RandomUtils.nextInt(0, 10));
		}
		smsCode = sb.toString();
		length=smsCode.length();
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.SECOND, 3600);
		validDate = cal.getTime();
		canSendDate = Calendar.getInstance();
	}

	public boolean verify(String mobile2, String code) {
		return mobile2 != null && mobile2.equals(mobile) && code != null && code.equals(smsCode);
	}

	/**
	 * 每隔2秒允许发一次
	 */
	public boolean canSend() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MILLISECOND, 1);// 防止第一次请求或者服务器重启后生成的时间一样
		return canSendDate.before(cal);
	}

	/**
	 * 刚sms过，控制下节奏，控制为2秒
	 */
	public void sent() {
		canSendDate.add(Calendar.SECOND, 2);
	}

	/**
	 * 验证码有效期1小时
	 * 
	 * @param mobile2
	 */
	public boolean valid(String mobile2) {
		if (mobile2 == null || !mobile2.equals(mobile))
			return false;
		return validDate.after(new Date());
	}

	public String getSmsCode() {
		return smsCode;
	}

	public void setSmsCode(String smsCode) {
		this.smsCode = smsCode;
	}

	public Date getValidDate() {
		return validDate;
	}

	public void setValidDate(Date validDate) {
		this.validDate = validDate;
	}

	public Calendar getCanSendDate() {
		return canSendDate;
	}

	public void setCanSendDate(Calendar canSendDate) {
		this.canSendDate = canSendDate;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public Integer getLength() {
		return length;
	}

	public void setLength(Integer length) {
		this.length = length;
	}
}